import json
import utils.html_parser as html_parser
import utils.pre_process as pre_process
from utils.code_parser import Parser

dir_path="./auto_test"

def auto_test():
    dir_list=[x for x in os.listdir(dir_path) if x!= 'Configure.data' and x!= 'DictPrj.data' and x!= 'success.txt']
    #dir_list = [x for x in dir_list if x == '82-fail']
    fail_num=0
    for index,dir_name in enumerate(dir_list):
        dict_file_path=os.path.join(dir_path,dir_name,"DictFile.data")
        pseudo_code_file_path=os.path.join(dir_path,dir_name,"StandardPsedoFile.code")
        data={"project_dict":""}
        flag = True
        try:
            with open(dict_file_path, 'r',encoding="utf-8") as f:
                dict_str=f.read()
                if dict_str!="":
                    data["dict"]=json.loads(dict_str).get("latexModel","")
            with open(pseudo_code_file_path, 'r',encoding="utf-8") as f:
                data["pseudoCode"]=f.read()
            with open(os.path.join(dir_path,"Configure.data"), 'r',encoding="utf-8") as f:
                configure_str=f.read()
                if configure_str!="":
                    configure_dict=json.loads(configure_str).get("latexModel","")
                    data["configure_dict"]=configure_dict
        except Exception as e:
            print("项目{}的数据读取失败，原因{}".format(dir_name,e))
            fail_num+=1
            flag = False
        ccode=get_code(data)
        if ccode.lstrip().startswith("ERROR"):
            print("项目{}的代码生成失败，原因{}".format(dir_name,ccode))
            fail_num+=1
            flag = False

        ccode_file_path=os.path.join(dir_path,dir_name,"CodeFile.c")
        with open(ccode_file_path, 'w',encoding="utf-8") as f:
            f.write(ccode)
        if flag:
            with open(os.path.join(dir_path,"success.txt"), 'a',encoding="utf-8") as f:
                f.write(dir_name+"\n")
        print("项目{}的代码已生成，进度{}/{},其中成功{}个，失败{}个".format(dir_name,index+1,len(dir_list),index+1-fail_num,fail_num))


def get_code(params):
    try:
        config_path= '../configs/dicts/config_tmp.json'  # 临时保存json文件
        module_dict_str=pre_process.pre_process(params["dict"],True)
        if module_dict_str=="":
            module_dict_json=[{},{},{},{},"数据字典为空"]
        else:
            module_dict_json = html_parser.str_to_json_502_new(module_dict_str)
        project_dict_str=pre_process.pre_process(params["project_dict"])
        if project_dict_str!="":
            project_dict_json=html_parser.str_to_json_502_new(project_dict_str)
            module_dict_json = html_parser.merge_json(project_dict_json,module_dict_json) # merge json
            if type(module_dict_json)==str and module_dict_json.startswith("ERROR"):
                return module_dict_json

        # 合并domainknowledge
        config_dict_str=params["configure_dict"]
        config_dict_str=pre_process.pre_process(config_dict_str,True)
        under_func_res,macro_res,key_word_config=html_parser.domain_to_json_502(config_dict_str)
        under_func_res.update(module_dict_json[1])
        module_dict_json[1]=under_func_res
        for key in macro_res.keys():
            if key in module_dict_json[2].keys():
                return "ERROR:宏常量中有重复的参数名 {}".format(key)
        macro_res.update(module_dict_json[2])
        module_dict_json[2]=macro_res

        key_words=key_word_config
        config_json=module_dict_json
        table_str=config_dict_str+project_dict_str+module_dict_str

        with open(config_path, 'w',encoding="utf-8") as f:
            json.dump(config_json, f,ensure_ascii=False)
        pseudoCode = pre_process.pre_process(params["pseudoCode"])
        pseudoCode = pre_process.add_semicolon(pseudoCode)
        lines = pseudoCode.split("\r\n")
        func_statment = ""
        func_pseudo_code = ""
        res_code = ""
        for line in lines:
            if line.strip().startswith("###") and line.strip().endswith("###;"):
                if func_pseudo_code.strip():
                    parser = Parser(func_pseudo_code,config_path,key_words= key_words)
                    parser.parse()
                    if func_statment != "":
                        res_code += func_statment + "\r\n{"
                    res_code += parser.print_codes() + "\r\n"
                    if func_statment != "":
                        res_code += "return ;\r\n}\r\n\r\n"
                func_pseudo_code = ""
                func_statment = line[line.find("###")+3:line.rfind("###")] 
            else :
                func_pseudo_code += line + "\r\n"
                
        if func_pseudo_code.strip():
            parser = Parser(func_pseudo_code,config_path,key_words= key_words)
            parser.parse()
            if func_statment != "":
                res_code += func_statment + "\r\n{"
            res_code += parser.print_codes() + "\r\n"
            if func_statment != "":
                res_code += "return ;\r\n}\r\n"

        return res_code
    except Exception as e:
        return "ERROR:" + str(e)

def get_code_from_qianwen():
    dir_list=[x for x in os.listdir(dir_path) if x!= 'Configure.data' and x!= 'DictPrj.data' and x!= 'success.txt']
    for index,dir_name in enumerate(dir_list):
        print("开始生成项目{}的标准伪代码".format(dir_name))
        with open(os.path.join(dir_path,dir_name,"StandardPsedoFile.code"), 'r',encoding="utf-8") as f:
            standard_pseudo = f.read()
            if standard_pseudo!="":
                continue
        pseudo_code_file_path=os.path.join(dir_path,dir_name,"PsedoFile.code")
        with open(pseudo_code_file_path, 'r',encoding="utf-8") as f:
            pseudo_code = f.read()
            if pseudo_code!="":
                pseudo_code = json.loads(pseudo_code)["latexModel"]
        round_num=3
        while round_num>0:
            standard_pseudo=request_qianwen(pseudo_code)
            if standard_pseudo.startswith("ERROR"):
                round_num-=1
            else:
                break        
        if standard_pseudo.startswith("ERROR"):
            print("项目{}的标准伪代码生成失败，原因{}".format(dir_name,standard_pseudo))

        # 获取markdown中的最后一段代码片段
        if standard_pseudo.find("```") != -1:
            standard_pseudo = standard_pseudo.split("```")[-2]
            standard_pseudo = standard_pseudo[standard_pseudo.find("\n")+1:]
            standard_pseudo = standard_pseudo.replace("$","")
        print(standard_pseudo)
        standard_pseudo_file_path=os.path.join(dir_path,dir_name,"StandardPsedoFile.code")
        with open(standard_pseudo_file_path, 'w',encoding="utf-8") as f:
            f.write(standard_pseudo)
        print("项目{}的标准伪代码已生成，进度{}/{}".format(dir_name,index+1,len(dir_list)))
        

import requests
import os
from openai import OpenAI
from llm.qianwen_prompt import *
def request_qianwen(pseudo):
    try:
        client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
            # api_key=os.getenv("DASHSCOPE_API_KEY"), 
            api_key="sk-3f966520a2684aea9367de0ebe63508e",
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )
        completion = client.chat.completions.create(
            model="qwen2.5-72b-instruct", # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            messages=[
                {
                    'role': 'system', 
                    'content': qianwen_system_prompt
                },{
                    'role': 'user', 
                    'content': qianwen_default_prompt.replace("{{ input_suedo_code }}",pseudo)
                }],
            temperature=0.7,
            top_p=0
            )
        return completion.choices[0].message.content
    except Exception as e:
        return "ERROR:" + str(e)

if __name__ == '__main__':
    #get_code_from_qianwen()
    auto_test()